package com.hongdee.insurance.quotationitem.service.TInsuranceItemServiceImpl;

import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.insurance.Constant;
import com.hongdee.insurance.order.entity.TInsuranceOrder;
import com.hongdee.insurance.order.service.ITInsuranceOrderService;
import com.hongdee.insurance.order.service.ITInsuranceOrderStatsticsService;
import com.hongdee.insurance.quotationitem.dao.ITInsuranceQuotationItemDao;
import com.hongdee.insurance.quotationitem.entity.TInsuranceQuotationItem;
import com.hongdee.insurance.quotationitem.service.ITInsuranceQuotationItemService;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr. Xu on 2017/4/27.
 */
@Service
public class TInsuranceQuotationItemServiceImpl implements ITInsuranceQuotationItemService {
    @Autowired
    private ITInsuranceQuotationItemDao itInsuranceQuotationItemDao;
    private String tabName = "T_Insurance_Quotation_Item";
    @Autowired
    private ITInsuranceOrderService orderService;

    /**
     * 根据报价单查询所有项目
     *
     * @param uid
     * @param quotationId
     * @return
     * @throws Exception
     */
    @Override
    public List QuotationItemList(String uid, String quotationId) throws Exception {
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" select * from " + tabName)
                .append(" where quotation_id = ? ");
        List params = new ArrayList();
        params.add(quotationId);
        return this.itInsuranceQuotationItemDao.list(sqlBuf.toString(), params.toArray());
    }

    /**
     * 退单选择保险项目
      * @param uid
     * @param quotationId
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public List quotationItemReturnList(String uid,String quotationId,String orderId)throws Exception{
        TInsuranceOrder order=orderService.getInfo(orderId);
        if(order!=null) {
            //判断是追加还是默认
            String oId="";
            String qId="";
            if(order.getInsuranceType().equals(String.valueOf(Constant.INSURNACE_TYPE.add.ordinal()))){
                oId=order.getInsuranceId();
                TInsuranceOrder parentOrder=orderService.getInfo(oId);
                qId=parentOrder.getQuotationId();
            }
            if(order.getInsuranceType().equals(String.valueOf(Constant.INSURNACE_TYPE.def.ordinal()))){
                oId=order.getId();
                qId=order.getQuotationId();
            }
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT * FROM(" +
                    " SELECT MAX(item_limit) item_limit,item_id,item_name,SUM(item_price) item_price,quotation_id FROM" +
                    " t_insurance_quotation_item WHERE quotation_id IN (" +
                    " SELECT '" + qId + "' id" +
                    " UNION" +
                    " SELECT quotation_id FROM t_insurance_order" +
                    " WHERE insurance_type = ? AND insurance_id = ?) GROUP BY item_id" +
                    " )  quotation_item WHERE NOT EXISTS (" +
                    " SELECT * FROM t_insurance_quotation_item WHERE quotation_id IN (" +
                    " SELECT quotation_id FROM t_insurance_order WHERE" +
                    " insurance_type = ? AND insurance_id = ? ) AND quotation_item.item_id = item_id)");
            return this.itInsuranceQuotationItemDao.list(sql.toString(), Constant.INSURNACE_TYPE.add.ordinal(), oId,
                    Constant.INSURNACE_TYPE.back.ordinal(), oId);
        }
        return new ArrayList();
    }

    /**
     * 查询退单剩余的保险项目
     * @param oldOrder
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public List surplusOrderItems(TInsuranceOrder oldOrder,String type) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT * FROM(" +
                " SELECT MAX(item_limit) item_limit,item_id,item_name,SUM(item_price) item_price,quotation_id FROM" +
                " t_insurance_quotation_item WHERE quotation_id IN (" +
                " SELECT '" + oldOrder.getQuotationId() + "' id" +
                " UNION" +
                " SELECT quotation_id FROM t_insurance_order" +
                " WHERE insurance_type = ? AND insurance_id = ?) GROUP BY item_id" +
                " )  quotation_item WHERE NOT EXISTS (" +
                " SELECT * FROM t_insurance_quotation_item WHERE quotation_id IN (" +
                " SELECT quotation_id FROM t_insurance_order WHERE" +
                " insurance_type = ? AND insurance_id = ? ) AND quotation_item.item_id = item_id)");
        if(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()).equals(type)){
            sql.append(" and item_id<2 ");
        }
        if(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()).equals(type)){
            sql.append(" and item_id>2 ");
        }
        return this.itInsuranceQuotationItemDao.list(sql.toString(), Constant.INSURNACE_TYPE.add.ordinal(), oldOrder.getId(),
                Constant.INSURNACE_TYPE.back.ordinal(), oldOrder.getId());
    }

    /**
     * 计算保单未退项目的总保费信息
     * @param uid
     * @param quotationId
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Float quotationItemReturnSumPrice(String uid,String quotationId,String orderId)throws Exception{
        TInsuranceOrder order=orderService.getInfo(orderId);
        if(order!=null) {
            //判断是追加还是默认
            String oId="";
            String qId="";
            if(order.getInsuranceType().equals(String.valueOf(Constant.INSURNACE_TYPE.add.ordinal()))){
                oId=order.getInsuranceId();
                TInsuranceOrder parentOrder=orderService.getInfo(oId);
                qId=parentOrder.getQuotationId();
            }
            if(order.getInsuranceType().equals(String.valueOf(Constant.INSURNACE_TYPE.def.ordinal()))){
                oId=order.getId();
                qId=order.getQuotationId();
            }
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT ROUND(SUM(item_price),2) returnPrice FROM(" +
                    " SELECT MAX(item_limit) item_limit,item_id,item_name,SUM(item_price) item_price,quotation_id FROM" +
                    " t_insurance_quotation_item WHERE quotation_id IN (" +
                    " SELECT '" + qId + "' id" +
                    " UNION" +
                    " SELECT quotation_id FROM t_insurance_order" +
                    " WHERE insurance_type = ? AND insurance_id = ?) GROUP BY item_id" +
                    " )  quotation_item WHERE NOT EXISTS (" +
                    " SELECT * FROM t_insurance_quotation_item WHERE quotation_id IN (" +
                    " SELECT quotation_id FROM t_insurance_order WHERE" +
                    " insurance_type = ? AND insurance_id = ? ) AND quotation_item.item_id = item_id)");
            Map infoMap=this.itInsuranceQuotationItemDao.info(sql.toString(), Constant.INSURNACE_TYPE.add.ordinal(), oId,
                    Constant.INSURNACE_TYPE.back.ordinal(), oId);
            if(infoMap.size()==0){
                return 0f;
            }else {
                if (infoMap.get("returnPrice") != null) {
                    return Float.valueOf(String.valueOf(infoMap.get("returnPrice")));
                }
                return 0f;
            }
        }
        return 0f;
    }


    /**
     * 根据车辆ID、报价单ID 查询最近一个报价单的保险项目信息
     * @param uid
     * @param carId
     * @return
     * @throws Exception
     */
    @Override
    public List findQuotationItemListBylately(String uid,String carId,String key,List<String> itemList) throws Exception {
        StringBuffer sql=new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append(" select * from t_insurance_quotation_item i where quotation_id=(" +
                " SELECT q.id FROM t_insurance_quotation q," +
                "   (SELECT COUNT(id) total,quotation_id FROM t_insurance_quotation_item GROUP BY quotation_id) item " +
                " WHERE" +
                " q.id = item.quotation_id AND item.total > 0 AND q.car_id=? ");
        if(key.equals("insurance")){
            sql.append(" and q.`status`=2 ");
        }

        sql.append(" order by " +
                " q.insurance_stop_date DESC LIMIT 1)");
        params.add(carId);
        if(itemList!=null){
            sql.append(" and i.item_id not in ( ");
            for(int i=0;i<itemList.size();i++){
                sql.append(" ? ");
                if(i<(itemList.size()-1)){
                    sql.append(" , ");
                }
                params.add(itemList.get(i));
            }
            sql.append(" ) ");
        }
        return this.itInsuranceQuotationItemDao.list(sql.toString(),params.toArray());
    }

    /**
     * 新的公司与上一个报价单 保险单 验证模板是否一致
     * @param uid
     * @param carId
     * @param key
     * @param insuranceCompanyId
     * @return
     * @throws Exception
     */
    @Override
    public List findQuotationItemListByLateLy(String uid,String carId,String key,String insuranceCompanyId) throws Exception {
        //取出最后一次的报价单或保险单信息
        List<Map<String,Object>> companyList=this.findCompanys(carId,key,insuranceCompanyId);
        //判断返回值是几条，如果小于2则说明 没有报价单或已出单的保险单
        if(companyList.size()<2){
            Map<String,Object> companyOld=companyList.get(0);
            //如果只有一条 判断 该条信息返回的ID是否与传入的ID一致则返回空数据
            if(insuranceCompanyId.equals(StringUtil.formatEmpty(companyOld.get("id")))){
                return new ArrayList();
            }else {
                //如果不一致 则有可能公司ID输入错 返回上一个的保险单 或报价单的项目
                return findQuotationItemListBylately(uid,carId,key,null);
            }
        }
        //判断模板是否一致
        Map<String,Object> companyOld=companyList.get(0);
        Map<String,Object> companyNew=companyList.get(1);
        //判断两个公司模板是否一致
        String templetOld=StringUtil.formatEmpty(companyOld.get("templet"));
        String templetNew=StringUtil.formatEmpty(companyNew.get("templet"));
        if(templetOld.equals(templetNew)){
            return findQuotationItemListBylately(uid,carId,key,null);
        }else {
            List<String> itemList=new ArrayList<>();
            //判断是分离 还是合并 0 不计免赔合并，1不计免赔分离
            if(templetOld.equals(String.valueOf(Constant.COMPANY_TEMPLET.hebin.ordinal()))){
                itemList.add("25");
            }

            if(templetOld.equals(String.valueOf(Constant.COMPANY_TEMPLET.fenli.ordinal()))){
                itemList.add("3");
                itemList.add("5");
                itemList.add("7");
                itemList.add("10");
                itemList.add("11");
                itemList.add("13");
                itemList.add("15");
                itemList.add("17");
            }
            //包含模板 去掉所有的不计免赔
            if(templetOld.equals(String.valueOf(Constant.COMPANY_TEMPLET.baohan.ordinal()))){
                itemList.add("3");
                itemList.add("5");
                itemList.add("7");
                itemList.add("10");
                itemList.add("11");
                itemList.add("13");
                itemList.add("15");
                itemList.add("17");
                itemList.add("25");
            }
            return findQuotationItemListBylately(uid,carId,key,itemList);
        }
    }

    
    private List<Map<String,Object>> findCompanys(String carId,String key,String insuranceCompanyId) throws Exception {
        StringBuffer sql=new StringBuffer();
        sql.append("select * from t_insurance_company where id= (" +
                " SELECT q.insurance_company_id FROM" +
                " t_insurance_quotation q, (" +
                " SELECT COUNT(id) total, quotation_id FROM" +
                " t_insurance_quotation_item GROUP BY quotation_id" +
                " ) item" +
                " WHERE q.id = item.quotation_id AND item.total > 0" +
                " AND q.car_id =? ");
        if(key.equals("insurance")){
            sql.append(" and q.`status`=2 ");
        }
        sql.append(" ORDER BY q.insurance_stop_date DESC LIMIT 1" +
                " )" +
                " union ALL" +
                " select * from t_insurance_company where id=? ");
        return this.itInsuranceQuotationItemDao.list(sql.toString(),carId,insuranceCompanyId);
    }

    /**
     * 检测 保险项目并返回保单类别
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public String checkItems(List<Map<String,Object>> data) throws Exception {
        //保存报价单新保险项目
        int syCount=0;
        int jqCount=0;
        for (Map map : data) {
            if(Integer.valueOf(String.valueOf(map.get("id")))<2){
                jqCount++;
            }
            if(Integer.valueOf(String.valueOf(map.get("id")))>1){
                syCount++;
            }
        }
        String type="";
        if(jqCount>0 && syCount==0){
            type=String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal());
        }
        if(jqCount>0){
            if(jqCount<2){
                throw new Exception("请勾选车船使用税、交强险项目!!");
            }
        }
        if(jqCount==0 && syCount>0){
            type=String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal());
        }
        if(jqCount>0 && syCount>0){
            type=String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal());
        }
        return type;
    }


    /**
     * 保存报价单项目
     *
     * @param data
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public void saveOrUpdate(List<Map<String,Object>> data, String QuotationId, String uid) throws Exception {
        if (data.size() > 0) {
            //每次修改项目时，先根据报价单清空项目
            StringBuffer del = new StringBuffer();
            List params = new ArrayList();
            del.append("delete from " + tabName).append(" where quotation_id = ? ");
            params.add(QuotationId);
            this.itInsuranceQuotationItemDao.executeSQL(del.toString(), params.toArray());
            List<TInsuranceQuotationItem> entitys=new ArrayList<>();
            for (Map map : data) {
                TInsuranceQuotationItem entity = new TInsuranceQuotationItem();
                //项目id
                if(map.get("id")!=null&&!map.get("id").equals("")){
                    entity.setItemId(map.get("id").toString());
                }
                //项目名称
                if(map.get("name")!=null&&!map.get("name").equals("")){
                    entity.setItemName(map.get("name").toString());
                }
                //保险公司返回的的报价
                if(map.get("price")!=null&&!map.get("price").equals("")){
                    entity.setItemPrice(map.get("price").toString());
                }
                //保额
                if(map.get("limit")!=null&&!map.get("limit").equals("")){
                    entity.setItemLimit(map.get("limit").toString());
                }
                //类型(0交强1商业)
                if(map.get("type")!=null&&!map.get("type").equals("")){
                    entity.setType(map.get("type").toString());
                }
                //
                if(!QuotationId.equals("")){
                    entity.setQuotationId(QuotationId);
                }
                entity.setCreateUser(uid);
                entity.setCompanyId(TokenUtil.getCompanyId(uid));
                entitys.add(entity);
            }
            if(entitys.size()>0) {
                this.itInsuranceQuotationItemDao.saveOrUpdateList(entitys);
            }
        }
    }

    private void updQuotationInsuranceType(int syCount,int jqCount,String quotationId) throws Exception {
        String type="";
        if(jqCount>0 && syCount==0){
            type=String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal());
        }
        if(jqCount==0 && syCount>0){
            type=String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal());
        }
        if(jqCount>0 && syCount>0){
            type=String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal());
        }
        String sql="update T_Insurance_Quotation set iscompulsoryinsurance=? where id=?";
        this.itInsuranceQuotationItemDao.executeSQL(sql,type,quotationId);
    }

    /**
     * 修改保险项目 根据具体的商业或交强进行修改
     * @param data
     * @param QuotationId
     * @param uid
     * @param type
     * @throws Exception
     */
    @Override
    public void updateItem(List<Map<String,Object>> data, String QuotationId, String uid,String type) throws Exception {
        if (data.size() > 0) {
            //每次修改项目时，先根据报价单清空项目
            StringBuffer del = new StringBuffer();
            List params = new ArrayList();
            del.append("delete from " + tabName).append(" where quotation_id = ? and type=? ");
            params.add(QuotationId);
            params.add(type);//0交强 1 商业
            this.itInsuranceQuotationItemDao.executeSQL(del.toString(), params.toArray());
            //保存报价单新保险项目
            int syCount=0;
            int jqCount=0;
            for (Map map : data) {
                if(type.equals(StringUtil.formatEmpty(map.get("type")))) {
                    TInsuranceQuotationItem entity = new TInsuranceQuotationItem();
                    //项目id
                    if (!"".equals(StringUtil.formatEmpty(map.get("id")))) {
                        entity.setItemId(map.get("id").toString());
                        if(Integer.valueOf(String.valueOf(map.get("id")))<2){
                            jqCount++;
                        }
                        if(Integer.valueOf(String.valueOf(map.get("id")))>1){
                            syCount++;
                        }
                    }
                    //项目名称
                    if (!"".equals(StringUtil.formatEmpty(map.get("name")))) {
                        entity.setItemName(map.get("name").toString());
                    }
                    //保险公司返回的的报价
                    if (!"".equals(StringUtil.formatEmpty(map.get("price")))) {
                        entity.setItemPrice(map.get("price").toString());
                    }
                    //保额
                    if (!"".equals(StringUtil.formatEmpty(map.get("limit")))) {
                        entity.setItemLimit(map.get("limit").toString());
                    }
                    //类型(0交强1商业)
                    if (!"".equals(StringUtil.formatEmpty(map.get("type")))) {
                        entity.setType(map.get("type").toString());
                    }
                    //
                    if (!QuotationId.equals("")) {
                        entity.setQuotationId(QuotationId);
                    }
                    entity.setCreateUser(uid);
                    entity.setCompanyId(TokenUtil.getCompanyId(uid));
                    this.itInsuranceQuotationItemDao.saveOrUpdate(entity);
                    this.updQuotationInsuranceType(syCount,jqCount,QuotationId);
                }
            }
        }
    }


    
    /***
     * 所有保险项目
     * @return
     * @throws Exception
     */
    @Override
    public List quotationList() throws Exception {
        StringBuffer sqlItemList = new StringBuffer();
        sqlItemList.append("select * from t_bc_newdict where p_code in ('syItem','jqItem')");
        return this.itInsuranceQuotationItemDao.list(sqlItemList.toString(), "");
    }

    /**
     * 查询已有保险项目
     */
    @Override
    public List hasQuotationList(String type, String id) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from " + tabName + " where quotation_id = ? ");

        return this.itInsuranceQuotationItemDao.list(sql.toString(), id);
    }

    /**
     * 单条保险项目保存
     */
    @Override
    public void singleSave(TInsuranceQuotationItem data, String uid) throws Exception {
        data.setCreateUser(uid);
        Map map = this.itInsuranceQuotationItemDao.info("t_bc_newdict", "id", data.getItemId());
        data.setItemName(map.get("label").toString());
        this.itInsuranceQuotationItemDao.saveOrUpdate(data);
    }

    /**
     * 单条保险项目删除
     */
    @Override
    public void singleDel(String id) throws Exception {
        this.itInsuranceQuotationItemDao.executeSQL("delete from " + tabName + " where id = ? ", id);
    }

    /**
     * 交强险项目
     * @param quotationId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String,Object>> findQuotationJqItem(String quotationId) throws Exception {
        String sql="select * from t_insurance_quotation_item where quotation_id=? and item_id < 2";
        return this.itInsuranceQuotationItemDao.list(sql,quotationId);
    }

    /**
     * 商业险项目
     * @param quotationId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String,Object>> findQuotationSyItem(String quotationId) throws Exception {
        String sql="select * from t_insurance_quotation_item where quotation_id=? and item_id > 1 ";
        return this.itInsuranceQuotationItemDao.list(sql,quotationId);
    }
}
